package com.wwx.demo.servlet;

import com.alibaba.fastjson.JSON;
import com.wwx.demo.entity.Result;
import com.wwx.demo.entity.Tiger;
import com.wwx.demo.service.api.TigerService;
import com.wwx.demo.service.impl.TigerServiceImpl;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.util.List;

@WebServlet(name = "TigerServletGetAll", value = "/TigerServletGetAll")
public class TigerServletGetAll extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、创建 Service 对象
        TigerService tigerService = new TigerServiceImpl();

        // 2、调用 Service 方法查询数据
        List<Tiger> tigerList = tigerService.getAllTigerList();

        // 代码重构，把查询结果封装到Result对象中
        Result<List<Tiger>> result = Result.ok(tigerList);

        // 3、把查询结果数据转换为 JSON 字符串  (代码重构，把Result封装为JSON数据)
        String jsonString = JSON.toJSONString(result);

        // 4、把 JSON 字符串作为响应体返回给前端
        // [1]设置响应消息头，通过设置内容类型，告诉前端：响应体是 JSON 数据类型
        response.setContentType("application/json;charset=UTF-8");

        // [2]设置响应体
        response.getWriter().write(jsonString);
    }
}
